import zipfile
import pyzipper

def detect_zip_method(zip_file):
    try:
        with zipfile.ZipFile(zip_file, 'r') as zf:
            if any(info.flag_bits & 0x1 for info in zf.infolist()):  # Check if any file is encrypted
                return 'pyzipper'
            else:
                return 'zipfile'
    except zipfile.BadZipFile:
        print("Bad ZIP file")
        return None

def dictionary_attack(zip_file, dictionary_file):
    zip_method = detect_zip_method(zip_file)
    
    if zip_method == 'zipfile':
        print("Using zipfile module for extraction.")
        return dictionary_attack_with_zipfile(zip_file, dictionary_file)
    elif zip_method == 'pyzipper':
        print("Using pyzipper module for extraction.")
        return dictionary_attack_with_pyzipper(zip_file, dictionary_file)
    else:
        print("Unsupported ZIP file format.")
        return None

def dictionary_attack_with_zipfile(zip_file, dictionary_file):
    with zipfile.ZipFile(zip_file, 'r') as zf:
        with open(dictionary_file, 'r') as df:
            for line in df:
                password = line.strip()
                try:
                    zf.extractall(pwd=password.encode('utf-8'))
                    print(f"Password found: {password}")
                    return password
                except (RuntimeError, zipfile.BadZipFile):
                    pass
    print("Password not found.")
    return None

def dictionary_attack_with_pyzipper(zip_file, dictionary_file):
    with pyzipper.AESZipFile(zip_file, 'r') as zf:
        with open(dictionary_file, 'r') as df:
            for line in df:
                password = line.strip()
                try:
                    zf.extractall(pwd=password.encode('utf-8'))
                    print(f"Password found: {password}")
                    return password
                except (RuntimeError, pyzipper.BadZipFile, pyzipper.LargeZipFile):
                    pass
    print("Password not found.")
    return None

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        print("Usage: python Dictionary_Attack.py <zip_file_path> <dictionary_file_path>")
        sys.exit(1)
    zip_file_path = sys.argv[1]
    dictionary_file_path = sys.argv[2]
    found_password = dictionary_attack(zip_file_path, dictionary_file_path)
    if found_password:
        print(f"Successfully cracked the password: {found_password}")
    else:
        print("Failed to crack the password.")
        
        # pip install pyzipper
        # sansjtw